import React, { Fragment } from 'react'
import { connect } from 'dva'
import {
  Tabs,
  Form,
  Spin,
  Card,
  Input,
  Upload,
  Icon,
  message,
  Row,
  Col,
  Button,
  DatePicker,
  Divider,
  Radio,
  Modal,
  checkbox,
  Checkbox
} from 'antd'
// import Mods from './Agreement.jsx'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { uploadUrl } from '@/config'
import router from 'umi/router'
import CustomCard from '@/components/CustomCard'
import { LZFormItem } from '@/components/LZForm'
import moment from 'moment'
import { renderDescriptionsItems } from '@/components/LZDescriptions'
import busShopService from '@/services/busShop'
import { forIdCard, goToRouter } from '../../utils/utils'
import { View } from 'viser-react'
import QRCode from 'qrcode.react'
import config from '../Channel/ChannelList/config'

const { TabPane } = Tabs
const { RangePicker } = DatePicker
const FormItem = Form.Item

@connect()
@Form.create()
class ShopInfo extends React.PureComponent {
  state = {
    loading: false,
    uploading: false,
    detail: {},
    shopInfo: {},
    enterpriseInfo: {},
    shopEnterpriseCertificates: [],
    rentAudit: false,
    visible: false,
    personCaVisible: false,
    personCaData: {
      mobile: '', // 法人手机
      personalIdentity3Key: '', // 用于验证的key
      vcode: '' // 手机验证码
    },
    personCaCheck: false,
    captchaTips: {
      title: '获取验证码',
      disabled: false
    },
    captchaCount: 60,
    visiblesimg: false,
    visiblesQrcode: false
  }

  componentWillMount = () => {
    this.selectBusShopInfo()
  }

  selectBusShopInfo = () => {
    this.setState({
      loading: true
    })
    busShopService
      .selectBusShopInfo()
      .then(res => {
        this.setState({
          detail: res || {},
          shopInfo: res.shop || {},
          shopEnterpriseCertificates:
            (res.enterpriseInfoDto &&
              res.enterpriseInfoDto.shopEnterpriseCertificates) ||
            [],
          enterpriseInfo:
            (res.enterpriseInfoDto &&
              res.enterpriseInfoDto.shopEnterpriseInfos) ||
            {},
          rentAudit: res.shop && res.shop.rentAudit,
          personCaData: res.enterpriseInfoDto
            ? {
                mobile: res.enterpriseInfoDto.shopEnterpriseInfos.telephone,
                personalIdentity3Key: '',
                vcode: ''
              }
            : {}
        })
      })
      .finally(() => {
        this.setState({
          loading: false
        })
      })
  }

  handleSubmit = () => {
    const { detail, rentAudit } = this.state
    if (!detail) {
      message.error('请新增店铺信息')
      return
    }
    detail.shop.rentAudit = rentAudit
    busShopService.updateShopAndEnterpriseInfo(detail).then(res => {
      message.success('更新成功')
    })
  }

  handleCancel = () => {
    this.setState({
      rentAudit: this.state.shopInfo.rentAudit
    })
  }

  handleCancelImgModal = e => {
    this.setState({
      visiblesimg: false
    })
  }

  showImg = e => {
    this.setState({
      img: e,
      visiblesimg: true
    })
  }

  handleCancelQrcodeModal = e => {
    this.setState({
      visiblesQrcode: false
    })
  }

  showQrcode = e => {
    this.setState({
      visiblesQrcode: true
    })
  }

  handleEdit = () => {
    const { dispatch } = this.props
    goToRouter(dispatch, '/shop/info/addInfo')
  }

  handlePhoneExaminationChange = evt => {
    this.setState({
      rentAudit: evt.target.value
    })
  }

  renderShopInfo = () => {
    const { shopInfo } = this.state
    const shopField = [
      { label: '店铺名称', value: shopInfo.name },
      {
        label: '店铺客服电话',
        value: shopInfo.serviceTel
      },
      { label: '店铺联系邮箱', value: shopInfo.userEmail },
      {
        label: '店铺联系人姓名',
        value: shopInfo.userName
      },
      { label: '店铺联系人电话', value: shopInfo.userTel },
      { label: '店铺创建时间', value: shopInfo.createTime },
      {
        label: '支付宝账号',
        value: shopInfo.zfbCode
      },
      { label: '支付宝姓名', value: shopInfo.zfbName },
      // {
      //   label: '店铺合同',
      //   value: shopInfo.shopContractLink,
      //   render: shopInfo.shopContractLink ? (
      //     <a href={shopInfo.shopContractLink} target="_blank">
      //       《租赁商家入驻合作协议》
      //     </a>
      //   ) : (
      //     <a onClick={this.toSign}>点击签约</a>
      //   )
      // },
      {
        label: '店铺logo',
        value: shopInfo.logo,
        className: 'df',
        render: (
          <img
            src={shopInfo.logo}
            onClick={() => this.showImg(shopInfo.logo)}
            className="table-cell-img"
            alt=""
          />
        )
      },
      {
        label: '店铺描述',
        value: shopInfo.description,
        className: 'vertical-align-baseline'
      },
      // {
      //   label: '店铺二维码',
      //   value: shopInfo.shopId,
      //   className: 'vertical-align-baseline',
      //   render: <a onClick={this.showQrcode}>点击查看</a>
      // }
    ]
    return (
      <div>
        <Card
          bordered={false}
          style={{ marginTop: 20 }}
          title={<CustomCard title="店铺信息" />}
          extra={
            <a onClick={this.handleEdit}>
              <Icon type="edit" />
              修改
            </a>
          }
        >
          {renderDescriptionsItems(shopField)}
        </Card>
      </div>
    )
  }

  renderCompanyInfo = () => {
    const { enterpriseInfo, shopEnterpriseCertificates } = this.state
    const hasImgs =
      shopEnterpriseCertificates && shopEnterpriseCertificates.length > 1
    const getDate = date => {
      return date && date.substr(0, 10)
    }
    const companyField = [
      { label: '企业名称', value: enterpriseInfo.name },
      {
        label: '企业注册资金',
        value: enterpriseInfo.registrationCapital
      },
      { label: '营业执照号', value: enterpriseInfo.businessLicenseNo },
      {
        label: '营业执照地址',
        value: enterpriseInfo.licenseStreet
      },
      { label: '营业执照经营范围', value: enterpriseInfo.businessScope },
      {
        label: '营业执照有效时间',
        value: enterpriseInfo.licenseStart
          ? `${getDate(enterpriseInfo.licenseStart)}~${getDate(
              enterpriseInfo.licenseEnd
            )}`
          : '无'
      },
      { label: '企业所在地', value: enterpriseInfo.licenseProvinceStr + enterpriseInfo.licenseCityStr },
      {
        label: '营业执照照片',
        value: enterpriseInfo.licenseSrc,
        className: 'df',
        render: (
          <img
            onClick={() =>
              this.showImg(
                (hasImgs && shopEnterpriseCertificates[0].image) || undefined
              )
            }
            src={(hasImgs && shopEnterpriseCertificates[0].image) || undefined}
            className="w-146 h-77"
          />
        )
      },

    ]

    const corporateField = [
      { label: '法人姓名', value: enterpriseInfo.realname },
      {
        label: '法人身份证号',
        value: enterpriseInfo.identity
      },
      { label: '法人手机号', value: enterpriseInfo.telephone },
      {
        label: '法人身份证信息',
        value: enterpriseInfo.enterpriseName,
        render: (
          <div>
            <img
              src={
                (hasImgs && shopEnterpriseCertificates[1].image) || undefined
              }
              onClick={() =>
                this.showImg(
                  (hasImgs && shopEnterpriseCertificates[1].image) || undefined
                )
              }
              className="w-146 h-77"
              alt=""
            />
            <img
              src={
                (hasImgs && shopEnterpriseCertificates[2].image) || undefined
              }
              onClick={() =>
                this.showImg(
                  (hasImgs && shopEnterpriseCertificates[2].image) || undefined
                )
              }
              className="w-146 h-77"
              alt=""
            />
          </div>
        )
      },
      { label: '授权公章Id', value: enterpriseInfo.signAssignedSealId },
    ]

    return (
      <div>
        <Card
          bordered={false}
          style={{ marginTop: 20 }}
          title={<CustomCard title="企业信息" />}
          extra={
            <a onClick={this.handleEdit}>
              <Icon type="edit" />
              修改
            </a>
          }
        >
          {renderDescriptionsItems(companyField)}
          <Divider />
          {renderDescriptionsItems(corporateField)}
        </Card>
      </div>
    )
  }

  renderAudit = () => {
    const { form } = this.props
    const { rentAudit } = this.state
    return (
      <Card
        bordered={false}
        style={{ marginTop: 20 }}
        title={
          <CustomCard
            title="审核确认"
            isExplain
            // explain="仅允许商家或平台其中一方做订单电话审核，勿双重审核打扰用户，请谨慎选择"
          />
        }
        extra={
          <div className="df">
            <Button onClick={this.handleCancel}>取消</Button>
            <Button type="primary" onClick={this.handleSubmit}>
              确定
            </Button>
          </div>
        }
      >
        <Form layout="inline">
          <FormItem label="是否需要人工审核">
            <Radio.Group
              onChange={this.handlePhoneExaminationChange}
              value={rentAudit}
            >
              <Radio value={true}>是</Radio>
              <Radio value={false}>否</Radio>
            </Radio.Group>
          </FormItem>
        </Form>
      </Card>
    )
  }

  handleCance = e => {
    this.setState({
      visible: false
    })
  }

  showModal = () => {
    this.setState({
      visible: true
    })
  }

  handleOk = e => {
    console.log(e)
    this.setState({
      visible: false
    })
  }

  handelPersonCaCancels = e => {
    this.setState({
      personCaVisible: false
    })
  }

  // 发送验证码
  handelSendCaptcha = e => {
    console.log(e)
    const { personCaData } = this.state
    const data = {
      mobile: this.props.form.getFieldValue('ca.mobile')
    }
    busShopService.sendCaptcha(data).then(res => {
      personCaData.personalIdentity3Key = res
      message.success('验证码发送成功')
      this.countDown()
    })
  }

  countDown = e => {
    const { captchaCount } = this.state
    if (captchaCount === 1) {
      this.setState({
        captchaCount: 60,
        captchaTips: {
          title: '获取验证码',
          disabled: false
        }
      })
    } else {
      this.setState({
        captchaCount: captchaCount - 1,
        captchaTips: {
          title: captchaCount - 1 + '秒后重新获取',
          disabled: true
        }
      })
      setTimeout(() => this.countDown(), 1000)
    }
  }

  // 点击签约逻辑，
  // 1、判断法人手机号是否存在，不存在提示，存在进入下一步
  // 2、判断法人CA是否生成，如果已生成进入合同模板页面，如果CA未生成，弹出短信验证
  toSign = e => {
    const { enterpriseInfo } = this.state
    if (enterpriseInfo.telephone) {
      if (!enterpriseInfo.personCa) {
        this.setState({
          personCaVisible: true,
          personCaCheck: false
        })
      } else {
        router.push('/shop/info/Agreement')
      }
    } else {
      message.error('企业信息不完整，请先完善企业信息！')
    }
  }

  // 检验法人手机验证码
  handleVerifyMobileCode = e => {
    const { personCaData } = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const data = {
          vcode: this.props.form.getFieldValue('ca.captcha'),
          personalIdentity3Key: personCaData.personalIdentity3Key
        }

        busShopService.verifyMobileCode(data).then(res => {
          if (res) {
            message.success(
              `已成功为您发放CA证书，该证书存储在e签宝电子签约平台。仅在您同意的情况下，您的证书方可被调用签署相关电子合同等法律文件。`
            )
            setTimeout(() => {
              router.push('/shop/info/Agreement')
            }, 2000)
          } else {
            message.error(
              '法人手机号三要素验证码校验失败，请确认企业信息填写正确！'
            )
          }
        })
      }
    })
  }

  // 同意数字证书协议
  togglePersonCaCheck = e => {
    this.setState({
      personCaCheck: e.target.checked
    })
  }

  render() {
    const { loading } = this.state
    const { form } = this.props
    const { personCaData, captchaTips } = this.state
    const { getFieldDecorator } = form
    const formItemLayout = {
      labelCol: { span: 5, offset: 2 },
      wrapperCol: { span: 12, offset: 1 }
    }
    return (
      <PageHeaderWrapper title="店铺信息">
        <Spin spinning={loading}>
          {this.renderShopInfo()}
          {this.renderCompanyInfo()}
          {this.renderAudit()}
        </Spin>
        <Modal
          title="法人手机号签署校验"
          visible={this.state.personCaVisible}
          onCancel={this.handelPersonCaCancels}
          destroyOnClose
          footer={null}
        >
          <Form layout="horizontal">
            <LZFormItem
              label="法人手机号"
              field="ca.mobile"
              getFieldDecorator={getFieldDecorator}
              initialValue={personCaData.mobile}
              formItemLayout={formItemLayout}
              requiredMessage="请输入法人手机号"
            >
              <Input disabled />
            </LZFormItem>
            <LZFormItem
              label="手机验证码"
              field="ca.captcha"
              getFieldDecorator={getFieldDecorator}
              requiredMessage="请输入手机验证码"
              formItemLayout={formItemLayout}
            >
              <Row gutter={8}>
                <Col span={14}>
                  <Input />
                </Col>
                <Col span={10}>
                  <Button
                    disabled={captchaTips.disabled}
                    onClick={this.handelSendCaptcha}
                  >
                    {captchaTips.title}
                  </Button>
                </Col>
              </Row>
            </LZFormItem>
            <div>
              <Row style={{ textAlign: 'center', marginBottom: '20px' }}>
                <Checkbox
                  checked={this.state.personCaCheck}
                  onChange={this.togglePersonCaCheck}
                >
                  同意并接受{' '}
                  <a
                    href="https://bcwangluo.oss-cn-shanghai.aliyuncs.com/%E6%95%B0%E5%AD%97%E8%AF%81%E4%B9%A6%E4%BD%BF%E7%94%A8%E5%8D%8F%E8%AE%AE-%E5%86%B0%E8%8D%89.pdf"
                    target="_blank"
                  >
                    《数字证书使用协议》
                  </a>
                </Checkbox>
              </Row>
            </div>
            <div>
              <Row className="center">
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={!this.state.personCaCheck}
                  onClick={this.handleVerifyMobileCode}
                >
                  校验验证码
                </Button>
              </Row>
              <Row
                style={{
                  textAlign: 'center',
                  padding: '5px',
                  margin: '20px 0 0 0',
                  color: '#FFFFFF',
                  backgroundColor: '#08b9a5'
                }}
              >
                e签宝正在调用您的数字证书，您在安全的签约环境中，请放心签署！
              </Row>
            </div>
          </Form>
        </Modal>
        <Modal
          visible={this.state.visiblesimg}
          onCancel={this.handleCancelImgModal}
          destroyOnClose
          footer={null}
          width="70%"
        >
          <img src={this.state.img} alt="alt" style={{ width: '100%' }} />
        </Modal>
        <Modal
          visible={this.state.visiblesQrcode}
          onCancel={this.handleCancelQrcodeModal}
          destroyOnClose
          footer={null}
        >
          <p
            style={{ textAlign: 'center', color: '#027AFF', fontSize: '24px' }}
          >
            打开支付宝[扫一扫]
          </p>
          <p style={{ textAlign: 'center' }}>
            <QRCode
              value={
                `alipays://platformapi/startapp?appId=${config.appId}&page=pages/shops/index?shopId=` +
                this.state.shopInfo.shopId
              }
              renderAs="svg"
              level="H"
              size="300"
            />
          </p>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default ShopInfo
